package fr.unice.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fr.unice.client.AudioFile;
import fr.unice.client.AudioFileDTO;
import fr.unice.client.services.GtunesService;

/**
 * The server side implementation of the Gtunes RPC service.
 */
@SuppressWarnings("serial")
public class GtunesServiceImpl extends RemoteServiceServlet implements
		GtunesService {

	@SuppressWarnings("unchecked")
	public List<AudioFileDTO> getAudioFiles() {
		Collection<AudioFile> audioFiles = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			Query q = pm.newQuery(AudioFile.class);
			q.setOrdering("name");
			audioFiles = (List<AudioFile>) q.execute();
			audioFiles = pm.detachCopyAll(audioFiles);
		} finally {
			pm.close();
		}

		ArrayList<AudioFileDTO> list = new ArrayList<AudioFileDTO>();
		for (AudioFile af : audioFiles) {
			list.add(new AudioFileDTO(af.getId(), af.getName(), af.getArtist(),
					af.getAlbum(), af.getYear(), af.getTrackNumber(), af
							.getGenre(), af.getDuration(), af.getURI()));
		}

		return list;
	}
}
